package net.lab1024.sa.admin.module.business.pdf.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import net.lab1024.sa.admin.module.business.pdf.util.OcrPerformanceOptimizer;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * OCR性能监控 Controller
 *
 * @Author 1024创新实验室
 */
@Tag(name = "OCR性能监控")
@RestController
@RequestMapping("/business/pdf/performance")
public class OcrPerformanceController {

    @Resource
    private OcrPerformanceOptimizer performanceOptimizer;

    @GetMapping("/stats")
    @Operation(summary = "获取OCR性能统计信息")
    public ResponseDTO<Map<String, Object>> getPerformanceStats() {
        try {
            OcrPerformanceOptimizer.OcrPerformanceStats stats = performanceOptimizer.getPerformanceStats();
            String suggestions = performanceOptimizer.getOptimizationSuggestions();
            
            Map<String, Object> result = new HashMap<>();
            result.put("stats", stats);
            result.put("suggestions", suggestions);
            result.put("currentMemoryUsageMB", performanceOptimizer.getCurrentMemoryUsage() / 1024 / 1024);
            
            return ResponseDTO.ok(result);
        } catch (Exception e) {
            return ResponseDTO.userErrorParam(e.getMessage());
        }
    }

    @PostMapping("/reset")
    @Operation(summary = "重置性能统计信息")
    public ResponseDTO<String> resetStats() {
        try {
            performanceOptimizer.resetStats();
            return ResponseDTO.ok("性能统计信息已重置");
        } catch (Exception e) {
            return ResponseDTO.userErrorParam(e.getMessage());
        }
    }

    @GetMapping("/memory")
    @Operation(summary = "获取当前内存使用情况")
    public ResponseDTO<Map<String, Object>> getMemoryUsage() {
        try {
            Runtime runtime = Runtime.getRuntime();
            long totalMemory = runtime.totalMemory();
            long freeMemory = runtime.freeMemory();
            long usedMemory = totalMemory - freeMemory;
            long maxMemory = runtime.maxMemory();
            
            Map<String, Object> result = new HashMap<>();
            result.put("totalMemoryMB", totalMemory / 1024 / 1024);
            result.put("freeMemoryMB", freeMemory / 1024 / 1024);
            result.put("usedMemoryMB", usedMemory / 1024 / 1024);
            result.put("maxMemoryMB", maxMemory / 1024 / 1024);
            result.put("memoryUsagePercent", (double) usedMemory / totalMemory * 100);
            
            return ResponseDTO.ok(result);
        } catch (Exception e) {
            return ResponseDTO.userErrorParam(e.getMessage());
        }
    }
} 